/**
 * Created by caiyl13664 on 2018/4/9.
 */

/**
 * @Description: 获取sts临时凭证
 * @Return: stsAccessKeyId;      //临时身份accessKeyId
 * @Return: stsAccessKeySecret;  //临时身份accessKeySecret
 * @Return: stsSecurityToken;    //临时身份securityToken
 * @Return: stsExpirationTime;   //临时身份过期时间
 * @Param:
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 10:55
 */
function getStsInfo() {
    var stsInfo;
    $.ajax({
        dataType:"json",
        type:"post",
        url: basePath + "oss/getStsInfo",//接口服务器地址
        async: false,//同步
        success:function(response){
            //成功执行
            console.log(response);
            if(response && response.result && response.content){
                stsInfo = response.content;
            }
        },
        error:function(e){
            //失败执行
            toastr.error(e.status+','+ e.statusText);
        }
    });
    return stsInfo;
}

/**
 * @Description: 从远程oss获取图片信息
 * @Return: { "FileSize": {"value": "21839"},
                "Format": {"value": "jpg"},
                "ImageHeight": {"value": "267"},
                "ImageWidth": {"value": "400"},
                "ResolutionUnit": {"value": "1"},
                "XResolution": {"value": "1/1"},
                "YResolution": {"value": "1/1"} }
 * @Param: imgUrl-图片链接（string）
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 10:48
 */
function getImageInfoFromOss(imgUrl) {
    if(!imgUrl){
        toastr.error("无效地址");
        return null;
    }
    var imageInfo;
    $.ajax({
        dataType:"json",
        type:"post",
        url: basePath + "oss/getOssImageInfo",//接口服务器地址
        data:{"imgUrl" : encodeURI(imgUrl + "?x-oss-process=image/info")},//请求数据
        async: false,//同步
        success:function(response){
            //成功执行
            console.log(response);
            if(response && response.result && response.content){
                imageInfo = response.content;
            }
        },
        error:function(e){
            //失败执行
            toastr.error(e.status+','+ e.statusText);
        }
    });
    return imageInfo;
}

/**
 * @Description: 上传文件至oss（同步上传）
 * @Return: 回调至uploadSuccess方法
 * @Param: fileId 文件input的id（string）
 * @Param: isHtml 是否为html文件（布尔型）
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 13:05
 */
function uploadFileToOss(fileId, isHtml,uploadSuccess,uploadFail) {
    var stsInfo = getStsInfo();
    if(!stsInfo){
        toastr.error("sts授权凭证缺失");
    }
    try{
        var fileObj = document.getElementById(fileId);
        if(!fileObj){
            toastr.error("选择文件为空");
            return;
        }
        var file = fileObj.files[0];
        //获取文件后缀
        var fileSuffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
        //获取oss后缀
        var ossUploadInfo = getOssUploadInfo();
        if(!ossUploadInfo){
            toastr.error("信息有误");
            return;
        }
        var endpoint = isHtml ? ossUploadInfo.ossEndpointHtml : ossUploadInfo.ossEndpoint;
        var bucket = isHtml ? ossUploadInfo.ossKnowledgeBaseBucket : ossUploadInfo.ossBucket;
        var client = new OSS.Wrapper({
            accessKeyId: stsInfo.stsAccessKeyId,
            accessKeySecret: stsInfo.stsAccessKeySecret,
            stsToken: stsInfo.stsSecurityToken,
            endpoint: endpoint,
            bucket: bucket
        });
        // result = client.multipartUpload(ossUploadInfo.ossSuffix + fileSuffix, file, { progress: function* (p){console.log('Progress: ' + p);},meta: {year: 2017,people: 'test'},mime: 'image/jpeg'});
        var temp;
        var result = client.multipartUpload(ossUploadInfo.ossSuffix + fileSuffix, file).then(function (result) {
            console.log(result);
            console.log(result.url);
            result.fileUrl = ossUploadInfo.protocol + bucket + "." + endpoint + "/" + ossUploadInfo.ossSuffix + fileSuffix;
            //各业务实现改方法
            uploadSuccess(result);
        }).catch(function (err) {
            uploadFail();
            console.log(err);
        });
    } catch(e){
        uploadFail();
        console.log(e);
    }
    return result;
}

/**
 * @Description: 上传文件至oss（异步上传）
 * @Return: 回调至uploadSuccess方法
 * @Param: fileId 文件input的id（string）
 * @Param: isHtml 是否为html文件（布尔型）
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 13:05
 */
function uploadFileToOssSync(fileId, isHtml,uploadSuccess,uploadFail) {
    var stsInfo = getStsInfo();
    if(!stsInfo){
        toastr.error("sts授权凭证缺失");
    }
    try{
        var fileObj = document.getElementById(fileId);
        if(!fileObj){
            toastr.error("选择文件为空");
            return;
        }
        var file = fileObj.files[0];
        //获取文件后缀
        var fileSuffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
        //获取oss后缀
        var ossUploadInfo = getOssUploadInfo();
        if(!ossUploadInfo){
            toastr.error("信息有误");
            return;
        }
        console.log(ossUploadInfo);
        var endpoint = isHtml ? ossUploadInfo.ossEndpointHtml : ossUploadInfo.ossEndpoint;
        var bucket = isHtml ? ossUploadInfo.ossKnowledgeBaseBucket : ossUploadInfo.ossBucket;
        var client = new OSS.Wrapper({
            accessKeyId: stsInfo.stsAccessKeyId,
            accessKeySecret: stsInfo.stsAccessKeySecret,
            stsToken: stsInfo.stsSecurityToken,
            endpoint: endpoint,
            bucket: bucket
        });
        client.multipartUpload(ossUploadInfo.ossSuffix + fileSuffix, file).then(function (result) {
            console.log("这里是返回信息");
            console.log(result);
            result.fileUrl = ossUploadInfo.protocol + bucket + "." + endpoint + "/" + ossUploadInfo.ossSuffix + fileSuffix;
            console.log(result.fileUrl);
            //各业务实现改方法
            uploadSuccess(result);
        }).catch(function (err) {
            uploadFail();
            console.log(err);
        });
    } catch(e){
        uploadFail();
        console.log(e);
    }
}

/**
 * @Description: 上传文件至oss（异步上传）
 * @Return: 回调至uploadSuccess方法
 * @Param: fileId 文件input的id（string）
 * @Param: isHtml 是否为html文件（布尔型）
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 13:05
 */
function batchUploadFileToOssSync(fileId, isHtml,uploadSuccess,uploadFail) {
    var stsInfo = getStsInfo();
    if(!stsInfo){
        toastr.error("sts授权凭证缺失");
    }
    try{
        var fileObj = document.getElementById(fileId);
        if(!fileObj){
            toastr.error("选择文件为空");
            return;
        }
        var file = fileObj.files[0];
        //获取文件后缀
        var fileSuffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
        //获取oss后缀
        var ossUploadInfo = getOssUploadInfo();
        if(!ossUploadInfo){
            toastr.error("信息有误");
            return;
        }
        var endpoint = isHtml ? ossUploadInfo.ossEndpointHtml : ossUploadInfo.ossEndpoint;
        var bucket = isHtml ? ossUploadInfo.ossKnowledgeBaseBucket : ossUploadInfo.ossBucket;
        var client = new OSS.Wrapper({
            accessKeyId: stsInfo.stsAccessKeyId,
            accessKeySecret: stsInfo.stsAccessKeySecret,
            stsToken: stsInfo.stsSecurityToken,
            endpoint: endpoint,
            bucket: bucket
        });
        client.multipartUpload(ossUploadInfo.ossSuffix + fileSuffix, file).then(function (result) {
            console.log(result);
            console.log(result.url);
            result.fileUrl = ossUploadInfo.protocol + bucket + "." + endpoint + "/" + ossUploadInfo.ossSuffix + fileSuffix;
            //各业务实现改方法
            uploadSuccess(result);
        }).catch(function (err) {
            uploadFail();
            console.log(err);
        });
    } catch(e){
        uploadFail();
        console.log(e);
    }
}

/**
 * @Description: 获取待上传oss文件信息
 * @Return: ossSuffix oss文件后缀
 * @Return: ossEndpoint
 * @Return: ossEndpointHtml
 * @Return: protocol
 * @Param:
 * @Author: caiyl@hsyuntai.com
 * @Date: 2018/4/11 13:45
 */
function getOssUploadInfo() {
    var ossUploadInfo;
    $.ajax({
        dataType:"json",
        type:"post",
        url: basePath + "oss/getOssSuffix",//接口服务器地址
        async: false,//同步
        // data: {"bucketName": bucketName},
        success:function(response){
            //成功执行
            console.log(response);
            if(response && response.result && response.content){
                ossUploadInfo = response.content;
            }
        },
        error:function(e){
            //失败执行
            toastr.error(e.status+','+ e.statusText);
        }
    });
    return ossUploadInfo;
}